package com.example.mywanandroid.ui.nav.mine.coinrank;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.mywanandroid.base.viewmodel.BaseViewModel;
import com.example.mywanandroid.bean.responsebean.CoinRankBean;
import com.example.mywanandroid.config.LoadState;
import com.example.mywanandroid.http.data.HttpDisposable;
import com.example.mywanandroid.http.request.HttpFactory;
import com.example.mywanandroid.http.request.HttpRequest;
import com.example.mywanandroid.util.CommonUtils;
import com.example.mywanandroid.util.NetworkUtils;

import java.util.ArrayList;
import java.util.List;

public class CoinRankViewModel extends BaseViewModel {

    private MutableLiveData<CoinRankBean> mRankList;
    private List<CoinRankBean.RankDataBean> mList;
    private int mPage;

    public CoinRankViewModel() {
        mRankList = new MutableLiveData<>();
        mList = new ArrayList<>();
        mPage = 1;
    }

    public LiveData<CoinRankBean> getCoinRankList() {
        return mRankList;
    }

    public void refreshData(boolean refresh) {
        if (refresh) {
            mPage = 1;
        } else {
            mPage++;
        }
        mRefresh = true;
        queryCoinRankList();
    }


    public void loadData() {
        loadState.postValue(LoadState.LOADING);
        mPage = 1;
        mRefresh = false;
        queryCoinRankList();
    }

    private void queryCoinRankList() {

        if (!NetworkUtils.isConnected()) {
            loadState.postValue(LoadState.NO_NETWORK);
            return;
        }

        HttpRequest.getInstance()
                .queryCoinRankList(mPage)
                .compose(HttpFactory.schedulers())
                .subscribe(new HttpDisposable<CoinRankBean>() {
                    @Override
                    public void success(CoinRankBean coinRankBean) {

                        if (CommonUtils.isListEmpty(coinRankBean.getDatas())) {
                            loadState.postValue(LoadState.NO_DATA);
                            return;
                        }
                        loadState.postValue(LoadState.SUCCESS);

                        if (mPage == 0) {
                            mList.clear();
                            mList.addAll(coinRankBean.getDatas());
                            mRankList.postValue(coinRankBean);
                        } else {
                            mList.addAll(coinRankBean.getDatas());
                            coinRankBean.setDatas(mList);
                            mRankList.postValue(coinRankBean);
                        }
                    }
                });
    }
}
